package com.bobi.ecofavor.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.bobi.ecofavor.common.enums.CacheKeyEnum;
import com.bobi.ecofavor.common.request.LoginModel;
import com.bobi.ecofavor.common.manager.WechatManager;
import com.bobi.ecofavor.common.utils.JsonResponse;
import com.bobi.ecofavor.common.utils.RedisUtil;
import com.bobi.ecofavor.model.domain.User;
import com.bobi.ecofavor.common.response.WxSessionResponse;
import com.bobi.ecofavor.service.ILoginService;
import com.bobi.ecofavor.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 功能描述
 */
@Slf4j
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private WechatManager wechatManager;

    @Resource
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WxSessionResponse doLogin(String code, User user) {


        log.info("当前微信登录code:{}", code);
        WxSessionResponse sessionCode = wechatManager.sessionCode(code);
        log.info("登录成功响应参数:{}", JSONObject.toJSONString(sessionCode));
        if (Objects.isNull(sessionCode)) {
            throw new RuntimeException("微信登录失败");
        }
        // 从数据库里根据OpenId查询User
        User userFromDB = userService.getUserByOpenId(sessionCode.getOpenId());
        // 如果 对象为空，则创建一个对象
        if (Objects.isNull(userFromDB)) {
            user.setWxOpenid(sessionCode.getOpenId());
            user.setWxSessionKey(sessionCode.getSessionKey());
            user.setCreateTime(LocalDateTime.now());
            userFromDB = user;
        } else {
            userFromDB.setNickname(user.getNickname())
                    .setProfilePhoto(user.getProfilePhoto())
                    .setUpdateTime(LocalDateTime.now());
            if (user.getPhoneNumber() != null && !"null".equals(user.getPhoneNumber()))
                userFromDB.setPhoneNumber(user.getPhoneNumber());
        }
        userService.saveOrUpdate(userFromDB);

        // 将当前用户存入redis
        redisUtil.set(CacheKeyEnum.USER.getKey(), userFromDB);

        // 返回相应对象
        sessionCode.setUid(userFromDB.getId());
        sessionCode.setPhoneNumber(userFromDB.getPhoneNumber());
        sessionCode.setNickname(userFromDB.getNickname());
        sessionCode.setAvatarUrl(userFromDB.getProfilePhoto());
        return sessionCode;
    }

    @Override
    public String getPhoneNumber(LoginModel request) {
        String accessToken = this.getAccessToken();
        String phoneNumber = wechatManager.getPhoneNumber(accessToken, request.getCode());
        User user = userService.getUserByOpenId(request.getOpenId());
        if (Objects.nonNull(user)) {
            user.setPhoneNumber(phoneNumber);
        }
        return phoneNumber;
    }

    @Override
    public void updateUserInfo(LoginModel request) {
        User user = userService.getUserByOpenId(request.getOpenId());
        if (Objects.nonNull(user)) {
            user.setProfilePhoto(request.getAvatarUrl());
            user.setNickname(request.getNickName());
            userService.updateById(user);
        }
    }

    @Override
    public LoginModel initUserInfo(LoginModel request) {
        String openId = request.getOpenId();
        if (openId == null || openId.isEmpty())
            return null;
        // 查询用户
        User user = userService.getUserByOpenId(openId);
        // 如果没有注册过
        if (user == null)
            return null;
        LoginModel loginModel = new LoginModel();
        loginModel.setAvatarUrl(user.getProfilePhoto());
        loginModel.setNickName(user.getNickname());
        loginModel.setPhoneNumber(user.getPhoneNumber());
        loginModel.setOpenId(null);
        return loginModel;
    }

    @Override
    public JsonResponse logout() {
        redisUtil.del(CacheKeyEnum.USER.getKey());
        return JsonResponse.success(null, "退出登录");
    }

    @Override
    public String getAccessToken() {
        return wechatManager.getAccessToken();
    }
}
